#!/usr/bin/env python
# -*-coding: utf8 -*-
'''
# created by: iori
# created on: Thu 19 Dec 2013 06:46:44 PM CST
'''
import sys
import re
import requests
from utils import magnet_hash
from xunlei import get_vod
DEBUG = 1

def coroutine(func):
    # an decorator to make an function become a coroutine
    def start(*args, **kwargs):
        cr = func(*args, **kwargs)
        cr.next()
        return cr
    return start

# coroutine template
@corontine
def skelton(target):
    # initialize
    while True:
        item = (yield) # wait for data
        # do something
        target.send(item)

@coroutine
def download(target):
    while True:
        item = (yield)
        headers={'Referer': item}
        rpos = item.rfind('/')
        down_url = item[:rpos].replace('file.php', 'down.php')
        print 'downloading: ', down_url
        tid = item[rpos+1:][:-5]
        data = {'type': 'torrent',
            'name': tid,
            'id': tid}
        response = requests.post(down_url, data=data, headers=headers)
        target.send(response.content)

@coroutine
def magnet_content(target):
    while True:
        response = (yield)
        magnet = magnet_hash(response)
        print 'get magnet: ', magnet
        target.send(magnet)

@coroutine
def upload():
    vod = get_vod()
    while True:
        magnet = (yield)
        print 'receive magnet: ', magnet
        print vod.add_magnet(magnet)

@coroutine
def grep(pat, target):
    match = re.compile(pat).search
    while True:
        source =  (yield)
        if match(source):
            print source
            target.send(source)



def extract(urls, target):
    needs = []
    sn = requests.session()
    sn.proxies = {'http': 'http://127.0.0.1:8087/'}
    for url in urls:
        content = sn.get(url).content
        links = re.findall(r'href="(http://[^"]+)', content)
        for link in links:
            target.send(link)

def main():
    extract(sys.argv[1:], grep('file.php', download(magnet_content(upload()))))
if __name__ == '__main__':
    main()
